package com.leng.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyUrlUtil {

	/**
	 * 从url中匹配请求uri（除去协议、域名、端口号和参数部分）
	 * 如url为http://192.168.10.36:2829/appweb/script/plugin/ueditor/jsp/upload1/20170901/41281504250668218.jpg?t=23
	 * 返回
	 * /appweb/script/plugin/ueditor/jsp/upload1/20170901/41281504250668218.jpg
	 * 
	 * @param url
	 * @param containProjectName
	 *            是否去掉项目名
	 * @return
	 */
	public static String getURI(String url, boolean containProjectName) {
		String regx = "(?:https?://)(?:(?:\\w+\\.){2,3}|[a-zA-Z0-9]+)(?:\\w+)(?::[0-9]+)?" + (containProjectName ? "(?:/\\w+/)" : "")
				+ "([^?]*)";
		Pattern p = Pattern.compile(regx);
		Matcher matcher = p.matcher(url);
		if (matcher.find()) {
			return matcher.group(1);
		}
		return null;
	}

	/**
	 * 匹配域名
	 * 如url为http://192.168.10.36:2829/appweb/script/plugin/ueditor/jsp/upload1/20170901/41281504250668218.jpg
	 * 返回192.168.10.36
	 * 
	 * @param url
	 * @return
	 */
	public static String getHost(String url) {
		Pattern p = Pattern.compile("(?:https?://)((\\w+\\.){2,3}\\w+|[a-zA-z0-9]+)(?::[0-9]+)?");
		Matcher matcher = p.matcher(url);
		if (matcher.find()) {
			return matcher.group(1);
		}
		return null;
	}

	public static void main(String[] args) {
		String path = "http://192.168.10.36:2829/appweb/script/plugin/ueditor/jsp/upload1/20170901/41281504250668218.jpg?t=23";
		System.out.println(getURI(path,true));
		System.out.println(getHost(path));
	}
}
